package node;

public class SingleLinkedList {
    private MyNode head = new MyNode(0);

    public void addNode(MyNode node){

        MyNode temp = head;
        while(true){
            if (temp.getNext() == null){
                break;
            }
            temp = temp.getNext();
        }

        temp.setNext(node);
    }

    //顺序添加节点
    public void sortNodeAdd(MyNode node){

        MyNode temp = head;
        Boolean flag = false;
        while(true){
            if (temp.getNext() == null){
                //遍历到最后了  还没有合适的  就放在最后面
                flag = true;
                break;
            }
            //如果temp下一个节点的值大于此时的node的值  则找到了要放置的位置
            if (head.getNext().getId()>node.getId()){
                flag = true;
                break;
            }
            if (temp.getId() == node.getId()){
                //如果 新节点的id与链表中的节点重复了  false
                flag = false;
                break;
            }


            temp = temp.getNext();
        }

        if (flag){
            //找到位置
            node.setNext(temp.getNext());
            temp.setNext(node);
        }else{
            throw new RuntimeException("节点重复 请从新输入节点");
        }
    }

    //删除一个节点
    public void deleteNode(int index){
        boolean flag = false;
        //如果 链表为空
        if (head.getNext() == null){
            flag = false;
        }

        MyNode temp = head;
        while (true){
            if (temp.getNext().getId() == index){
                flag = true;
                break;
            }
            temp = temp.getNext();
        }
        if (flag){
            //找到 即为此时的temp
            temp.setNext(temp.getNext().getNext());
        }else {
            //未找到
            throw new RuntimeException("无此节点");
        }
    }

    //修改一节点
    public void updateNode(MyNode node){
        MyNode temp  =head.getNext();
        boolean flag = false;
        while (true){
            if (temp.getId() == node.getId()){
                flag = true;
                break;
            }
            if (temp.getNext() == null){
                flag = false;
                break;
            }

            temp = temp.getNext();
        }
        if (flag){
            //找到相应的节点
            temp.setData(node.getData());
        }else{
            throw new RuntimeException("无此节点 ，请确认");
        }
    }
    public void list(){
        if (head.getNext() == null){
            System.out.println("链表为空");
            return;
        }
        MyNode temp  = head.getNext();
        int i = 0;
        while (true){
            if (temp == null){
                break;
            }
            i++;
            System.out.println("链表的第"+i+"个节点内容为"+temp.getData());
            temp = temp.getNext();
        }
    }
}
